#include "PropertyIndexerBuilder.h"

#include "ScriptCompiler/ScriptFileContext.h"

#include "ScriptCompiler/ASTBuilder/FunctionParameterBuilder.h"


CPropertyIndexerBuilder::CPropertyIndexerBuilder(std::shared_ptr<CScriptFileContext> InContext)
{
    Context = InContext;
}

bool CPropertyIndexerBuilder::ReadCurentToken()
{
    //read '['
    {
        auto Token = Context->GetCurrentToken();
        if(Token->Type != EScriptTokenType::LeftBracket)
        {
            Context->RaiseError(10085,Token,U"Expect '['");
            return false;
        }
        Context->CurrentTokenIndex++;


        Result= std::make_shared<CPropertyIndexerNode>(Context);
        Result->LeftBracket = Token;
    }

    
    //read parameters
    {
        //check if empty
        {
            auto Token = Context->GetCurrentToken();
            if(Token->Type == EScriptTokenType::RightBracket)
            {
                Result->RightBracket = Token;
                Context->CurrentTokenIndex++;

                Context->RaiseError(10086,Result->LeftBracket,U"Property indexer must have at least one parameter");
                return false;
            }
        }

        while(true)
        {
            
            
            //read parameter
            {
                auto ParameterBuilder = std::make_shared<CFunctionParameterBuilder>(Context);
                if(!ParameterBuilder->ReadCurentToken())
                {
                    return false;
                }

                Result->Parameters.Add(ParameterBuilder->Result);
            }

            //try read ','
            {
                auto Token = Context->GetCurrentToken();
                if(Token->Type == EScriptTokenType::Comma)
                {
                    //just skip
                    Context->CurrentTokenIndex++;
                }
                else if( Token->Type == EScriptTokenType::RightBracket)
                {
                    Result->RightBracket = Token;
                    Context->CurrentTokenIndex++;
                    return true;
                }
                else
                {
                    Context->RaiseError(10087,Token,U"Expect ',' or ']'");
                    return false;
                }
            }
        }

    }

    return false;

}
